<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import { message } from 'ant-design-vue';
import moment from "moment"

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const items = ref([]);
const loading = ref(true);
const confirmLoading = ref(false);
const totalItems = ref(0);
const pagination = computed(() => ({
    total: totalItems.value,
    current: pageNo.value,
    pageSize: pageSize.value
})) 
const queryParams = ref({
    goodsNumber: "",
    goodsName: "",
    commonName: "",
    startTime: "",
    endTime: ""
});
const columns = ref([
    {
        title: "商品编码",
        dataIndex: "goodsNumber",
        key: 'goodsNumber',
        resizable: true
    },
    {
        title: "商品名",
        dataIndex: "goodsName",
        key: 'goodsName',
        resizable: true
    },
    {
        title: "通用名称",
        dataIndex: "commonName",
        key: 'commonName',
        resizable: true
    },
    {
        title: "剂型",
        dataIndex: "medicineType",
        key: 'medicineType',
        align: "center",
        resizable: true
    },
    {
        title: "规格",
        dataIndex: "specifications",
        key: 'specifications',
        resizable: true
    },
    {
        title: "批准文号",
        dataIndex: "approvalNumber",
        key: 'approvalNumber',
        resizable: true
    },
    {
        title: "单位",
        dataIndex: "unit",
        key: 'unit',
        align: "center",
        resizable: true
    },
    {
        title: "生产企业",
        dataIndex: "produceFactory",
        key: 'produceFactory',
        resizable: true
    },
    {
        title: "产地",
        dataIndex: "produceAddress",
        key: 'produceAddress',
        resizable: true
    },
    {
        title: "分类存储",
        dataIndex: "saveCategory",
        key: 'saveCategory',
        align: "center",
        resizable: true
    },
    {
        title: "部门",
        dataIndex: "department",
        key: 'department',
        resizable: true
    },
    {
        title: "新增时间",
        dataIndex: "createTime",
        key: 'createTime',
        resizable: true
    },
    {
        title: "修改时间",
        dataIndex: "updateTime",
        key: 'updateTime',
        resizable: true
    },
    {
        title: "操作类型",
        dataIndex: "recordType",
        key: 'recordType'
    },
    {
        title: "操作时间",
        dataIndex: "recordTime",
        key: 'recordTime',
        resizable: true
    }
])
const columnsAdd = ref([
    {
        title: "商品编码",
        dataIndex: "goodsNumber",
        key: 'goodsNumber'
    },
    {
        title: "商品名",
        dataIndex: "goodsName",
        key: 'goodsName'
    },
    {
        title: "通用名称",
        dataIndex: "commonName",
        key: 'commonName'
    },
    {
        title: "剂型",
        dataIndex: "medicineType",
        key: 'medicineType',
        align: "center"
    },
    {
        title: "规格",
        dataIndex: "specifications",
        key: 'specifications'
    },
    {
        title: "批准文号",
        dataIndex: "approvalNumber",
        key: 'approvalNumber'
    },
    {
        title: "单位",
        dataIndex: "unit",
        key: 'unit',
        align: "center"
    },
    {
        title: "生产企业",
        dataIndex: "produceFactory",
        key: 'produceFactory'
    },
    {
        title: "产地",
        dataIndex: "produceAddress",
        key: 'produceAddress'
    },
    {
        title: "分类存储",
        dataIndex: "saveCategory",
        key: 'saveCategory',
        align: "center"
    },
    {
        title: "部门",
        dataIndex: "department",
        key: 'department'
    }
])
const open = ref(false);
const title = ref("");
const formData = ref({});

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page
    pageSize.value = itemsPerPage
    axios.post('/MedicineRecord/getMedicineRecordList', {
        page: page,
        pageSize: itemsPerPage,
        goodsNumber: queryParams.value.goodsNumber,
        goodsName: queryParams.value.goodsName,
        commonName: queryParams.value.commonName,
        startTime: queryParams.value.startTime ? moment(queryParams.value.startTime.$d).format("YYYY-MM-DD HH:mm:ss") : '',
        endTime: queryParams.value.endTime ? moment(queryParams.value.endTime.$d).format("YYYY-MM-DD HH:mm:ss"): ""
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
});

const dialogEnum = {
    update: "编辑",
    create: "新增"
}

function openData(data) {
    open.value = true
    title.value = dialogEnum.update
    formData.value = data
}

function submit() {
    if(title.value == dialogEnum.create) {
        confirmLoading.value = true
        axios.post("/User/addUser", formData.value).then(res => {
            if(res.data.code == 0) {
                message.success('新增成功！')
                confirmLoading.value = false;
                open.value = false;
                loadItems({page: 1, itemsPerPage: pageSize.value});
            } else {
                confirmLoading.value = false;
                message.error(res.data.message)
            }
        }, err => {
            confirmLoading.value = false;
            message.error(err.data.message)
        })
    } else if(title.value == dialogEnum.update) {
        confirmLoading.value = true
        axios.post("/Medicine/updateMedicine", formData.value).then(res => {
            if(res.data.code == 0) {
                message.success('修改成功！')
                confirmLoading.value = false;
                open.value = false;
                loadItems({page: 1, itemsPerPage: pageSize.value});
            } else {
                confirmLoading.value = false;
                message.error(res.data.message)
            }
        }, err => {
            confirmLoading.value = false;
            message.error(err.data.message)
        })
    }
}

function handleTabChange(pag){
    loadItems({page: pag.current, itemsPerPage: pag.pageSize})
}

function exportList() {
    axios({
        method: "post",
        url: "/Medicine/exportMedicineList",
        data: {
            page: pageNo.value,
            pageSize: pageSize.value,
            goodsNumber: queryParams.value.goodsNumber,
            goodsName: queryParams.value.goodsName,
            commonName: queryParams.value.commonName,
            startTime: queryParams.value.startTime ? moment(queryParams.value.startTime.$d).format("YYYY-MM-DD HH:mm:ss") : '',
            endTime: queryParams.value.endTime ? moment(queryParams.value.endTime.$d).format("YYYY-MM-DD HH:mm:ss"): ""
        },
        responseType: 'blob'
    }).then(({data}) => {}, err => {
        let blob = new Blob([err.data], {type: "application/vnd.ms-excel"});
        let fileName = `药品基础资料.xlsx`
        if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器
            const link = document.createElement("a"); // 创建a标签
            link.download = fileName; // a标签添加属性
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click(); // 执行下载
            URL.revokeObjectURL(link.href); // 释放url
            document.body.removeChild(link); // 释放标签
        } else {
            // 其他浏览器
            navigator.msSaveBlob(blob, fileName);
        }
    })
}

const fileList = ref([]);
function uploadFile(file) {
    var formData = new FormData();
    formData.append("file", file.file)
    axios({
        method: "post",
        url: "/Medicine/importMedicine",
        data: formData,
        headers: {
            'Content-Type': "multipart/form-data"
        }
    }).then(res => {
        message.success(res.data.message)
        loadItems({page: 1, itemsPerPage: pageSize.value});
    }, err => {
        message.error(err.data.message)
    })
}

const selectedRowKeys = ref([])
function onSelectChange(keys ) {
    selectedRowKeys.value = keys
}

function deleteList() {
    if(!selectedRowKeys.value.length) {
        message.error("请选择数据！")
        return
    }
    let obj = {
        medicineIdList: Object.values(selectedRowKeys.value)
    }
    axios.post('/Medicine/disableMedicineBatch', obj).then(res => {
        if(res.data.code == 0) {
            message.success('删除成功！')
            loadItems({page: 1, itemsPerPage: pageSize.value});
        } else {
            message.error(res.data.message)
        }
    }, err => {
        message.error(err.data.message)
    })
}

const addShow = ref(false);
const addList = ref([{}]);
const confirmLoadingAdd = ref(false);
function getAddShow() {
    addShow.value = true
    addList.value = [{}]
}

function addListPost() {
    let obj = {
        medicineList: addList.value
    }
    confirmLoadingAdd.value = true
    axios.post("/Medicine/addMedicineBatch", obj).then(res => {
        if(res.data.code == 0) {
            message.success('添加成功！')
            loadItems({page: 1, itemsPerPage: pageSize.value});
            confirmLoadingAdd.value = false
            addShow.value = false
        } else {
            message.error(res.data.message)
            confirmLoadingAdd.value = false
        }
    }, err => {
        message.error(err.data.message)
        confirmLoadingAdd.value = false
    })
}

function handleResizeColumn(w, col) {
  col.width = w;
}
</script>

<template>
    <a-spin size="large" :spinning="loading">
        <a-card title="药品基础资料历史记录">
            <a-row style="margin-bottom: 25px;">
                <a-form
                layout="inline"
                :model="queryParams"
                :colon="false">
                    <a-form-item label="商品编码" style="margin-bottom: 25px;">
                        <a-input v-model:value="queryParams.goodsNumber" placeholder="商品编码" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="商品名">
                        <a-input v-model:value="queryParams.goodsName" placeholder="商品名" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="通用名称">
                        <a-input v-model:value="queryParams.commonName" placeholder="通用名称" allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="开始时间">
                        <a-date-picker show-time v-model:value="queryParams.startTime" placeholder="开始时间"></a-date-picker>
                    </a-form-item>
                    <a-form-item label="结束时间">
                        <a-date-picker show-time v-model:value="queryParams.endTime" placeholder="结束时间"></a-date-picker>
                    </a-form-item>
                    <a-from-item>
                        <a-button @click="loadItems({page: 1, itemsPerPage: pageSize})">查询</a-button>
                    </a-from-item>
                </a-form>
            </a-row>
            <a-table
            @resizeColumn="handleResizeColumn"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            rowKey="medicineId"
            :dataSource="items"
            :columns="columns"
            :pagination="pagination"
            @change="handleTabChange">
                <template #bodyCell="{ column, text, record }">
                    <teamplte v-if="column.dataIndex == 'recordType'">
                        <span v-if="record.recordType == 1">修改</span>
                        <span v-if="record.recordType == 2">删除</span>
                    </teamplte>
                </template>
            </a-table>            
        </a-card>

        <a-modal
        v-model:open="addShow"
        title="基础资料"
        cancelText="关闭"
        okText="确定"
        width="66%"
        :confirmLoading="confirmLoadingAdd"
        @ok="addListPost">
            <a-table
            :dataSource="addList"
            :columns="columnsAdd"
            :pagination="{
                total: addList.length,
                current: 1,
                pageSize: 100
            }">
                <template #bodyCell="{column, text, record, index}">
                    <template v-if="column.dataIndex == 'goodsNumber'">
                        <a-input v-model:value="record.goodsNumber"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'goodsName'">
                        <a-input v-model:value="record.goodsName"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'commonName'">
                        <a-input v-model:value="record.commonName"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'medicineType'">
                        <a-input v-model:value="record.medicineType"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'specifications'">
                        <a-input v-model:value="record.specifications"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'approvalNumber'">
                        <a-input v-model:value="record.approvalNumber"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'unit'">
                        <a-input v-model:value="record.unit"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'produceFactory'">
                        <a-input v-model:value="record.produceFactory"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'produceAddress'">
                        <a-input v-model:value="record.produceAddress"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'saveCategory'">
                        <a-input v-model:value="record.saveCategory"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'department'">
                        <a-input v-model:value="record.department"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'action'">
                        <a style="color: red;" @click="addList.splice(index, 1)">删除</a>
                    </template>
                </template>
            </a-table>
            <a-button @click="addList.push({})">添加行</a-button>
        </a-modal>

        <a-modal
        v-model:open="open"
        :title="title"
        cancelText="关闭"
        okText="确定"
        :confirmLoading="confirmLoading"
        @ok="submit">
            <a-form
            :model="formData"
            :colon="false"
            :label-col="{ span: 5 }">
                <a-form-item
                label="商品编码"
                :rules="[{ required: true, message: '请输入商品编码！' }]">
                    <a-input
                    v-model:value="formData.goodsNumber"
                    placeholder="请输入商品编码"></a-input>
                </a-form-item>
                <a-form-item
                label="商品名"
                :rules="[{ required: true, message: '请输入商品名！' }]">
                    <a-input
                    v-model:value="formData.goodsName"
                    placeholder="请输入商品名"></a-input>
                </a-form-item>
                <a-form-item
                label="通用名称"
                :rules="[{ required: true, message: '请输入通用名称！' }]">
                    <a-input
                    v-model:value="formData.commonName"
                    placeholder="请输入通用名称"></a-input>
                </a-form-item>
                <a-form-item
                label="剂型"
                :rules="[{ required: true, message: '请输入商品类型！' }]">
                    <a-input
                    v-model:value="formData.medicineType"
                    placeholder="请输入商品类型"></a-input>
                </a-form-item>
                <a-form-item
                label="规格"
                :rules="[{ required: true, message: '请输入规格！' }]">
                    <a-input
                    v-model:value="formData.specifications"
                    placeholder="请输入规格"></a-input>
                </a-form-item>
                <a-form-item
                label="批准文号"
                :rules="[{ required: true, message: '请输入批准文号！' }]">
                    <a-input
                    v-model:value="formData.approvalNumber"
                    placeholder="请输入批准文号"></a-input>
                </a-form-item>
                <a-form-item
                label="单位"
                :rules="[{ required: true, message: '请输入单位！' }]">
                    <a-input
                    v-model:value="formData.unit"
                    placeholder="请输入单位"></a-input>
                </a-form-item>
                <a-form-item
                label="生产企业"
                :rules="[{ required: true, message: '请输入生产企业！' }]">
                    <a-input
                    v-model:value="formData.produceFactory"
                    placeholder="请输入生产企业"></a-input>
                </a-form-item>
                <a-form-item
                label="分类存储"
                :rules="[{ required: true, message: '请输入分类存储！' }]">
                    <a-input
                    v-model:value="formData.saveCategory"
                    placeholder="请输入分类存储"></a-input>
                </a-form-item>
                <a-form-item
                label="部门"
                :rules="[{ required: true, message: '请输入部门！' }]">
                    <a-input
                    v-model:value="formData.department"
                    placeholder="请输入部门"></a-input>
                </a-form-item>
            </a-form>
        </a-modal>
    </a-spin>
</template>

<style scoped lang="less">

</style>
